package likouJava;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class 合并区间 {
    public int[][] merge(int[][] intervals) {
        int n =intervals.length;
        //对区间排序
        Arrays.sort(intervals,(a,b) -> a[0] - b[0]);

        List<int[]> result = new ArrayList<>();
        int [] current = intervals[0];  //当前合并区间

        for (int i = 1; i < n; i++) {
            if(intervals[i][0] <= current[1]){
                //有重叠，更新右端点
                current[1] = Math.max(current[1], intervals[i][1]);
            }else {
                //无重叠 加入结果并更新当前区
                result.add(current);
                current = intervals[i];
            }
        }
        // 最后一个需要手动添加
        result.add(current);
        return result.toArray(new int[result.size()][]);
    }

}
